﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Windows.Forms;
using API;
using API.StoreWebService;
using DB;

namespace ProductManage
{
    public partial class FormEmail : Form
    {
        public FormEmail()
        {
            InitializeComponent();
        }

        private List<EmailInfo> GetEmailListFromDB()
        {
            var list = EmailsDb.DbMysql.GetMailChimpEmailList(2000);
            EmailsDb.DbMysql.UpdateMailChimpEmailLastSent(list);
            return list;
        }
        
        private void btnSave_Click(object sender, EventArgs e)
        {
            AddCidOnline(this.txtTitle.Text, this.txtSubject.Text, this.richTextBoxTemplate.Text);
        }
        private void AddCidOnline(string strTitle, string strSubject, string strTemplate)
        {
            var Api = MailChimpApi.GetApi(this.textBoxApiKey.Text);
            Dictionary<string, string> dic;
            Api.GetEmailList(out dic);
            if (dic.Count == 0)
            {
                return;
            }

            var iTemplate = Api.AddTemplates(strTitle, strTemplate);
            var campaignId = Api.CreateCampaign(strTitle.Trim(), strSubject.Trim(), dic.Keys.ToArray()[0], iTemplate);
            Api.SendCampaignSchedule(campaignId, this.dtpSendDate.Value.AddHours(7));
        }

        private void CopefirstOne(List<string> listFileNames)
        {
            string pic1 = "";
            string pic2 = "";
            string pic3 = "";
            string pic4 = "";
            foreach (var listFile in listFileNames)
            {
                if (listFile.Contains("_PIC1"))
                {
                    pic1 = listFile;
                }
                if (listFile.Contains("_PIC2"))
                {
                    pic2 = listFile;
                }
                if (listFile.Contains("_PIC3"))
                {
                    pic3 = listFile;
                }
                if (listFile.Contains("_PIC4"))
                {
                    pic4 = listFile;
                }
            }

            if (pic1 != "")
            {
                if (pic2!="") File.Delete(pic2);
                if (pic3 != "") File.Delete(pic3);
                if (pic4 != "") File.Delete(pic4);
                return;
            }
            if (pic2 != "")
            {
                File.Copy(pic2, pic2.Replace("_PIC2", "_PIC1"));
                if (pic2 != "") File.Delete(pic2);
                if (pic3 != "") File.Delete(pic3);
                if (pic4 != "") File.Delete(pic4);
                return;
            }
            if (pic3 != "")
            {
                File.Copy(pic3, pic3.Replace("_PIC3", "_PIC1"));
                if (pic3 != "") File.Delete(pic3);
                if (pic4 != "") File.Delete(pic4);
                return;
            }
            if (pic4 != "")
            {
                File.Copy(pic4, pic4.Replace("_PIC4", "_PIC1"));
                if (pic4 != "") File.Delete(pic4);
            }
        }
        private void buttonUpdateList_Click_1(object sender, EventArgs e)
        {
            var Api = MailChimpApi.GetApi(this.textBoxApiKey.Text);
            var listItem = (System.Collections.Generic.KeyValuePair<string, string>)this.comboBoxEmailList.SelectedItem;
            Api.BatchUnSubscribeList(listItem.Key);

            Api.BatchSubscribeToList(listItem.Key, GetEmailListFromDB());
        }

        private void buttonLoadList_Click(object sender, EventArgs e)
        {
            var Api = MailChimpApi.GetApi(this.textBoxApiKey.Text);
            Dictionary<string, string> dic;
            Api.GetLists(out dic);
            this.comboBoxEmailList.Items.Clear();
            foreach (var key in dic)
            {
                comboBoxEmailList.Items.Add(key);
            }
            comboBoxEmailList.DisplayMember = "Value";
        }
        private void buttonSaveAbuseList_Click(object sender, EventArgs e)
        {
            var listItem = (System.Collections.Generic.KeyValuePair<string, string>)this.comboBoxEmailList.SelectedItem;
            MailChimpApi.GetApi(this.textBoxApiKey.Text).SaveAbuseEmailToDb(listItem.Key);
        }

        #region SMTP
        private void SentGmail()
        {
            try
            {
                System.Net.Mail.MailMessage mailObj = new System.Net.Mail.MailMessage();
                mailObj.IsBodyHtml = true;
                mailObj.Subject = "邮件标题";
                mailObj.Body = "邮件正文";
                mailObj.To.Add("yongming1118@hotmail.com");
                System.Net.Mail.SmtpClient SmtpMail = new SmtpClient("smtp.gmail.com");
                mailObj.From = new MailAddress("yongming1118@gmail.com", "Alex", System.Text.Encoding.UTF8);
                SmtpMail.Credentials = new System.Net.NetworkCredential("yongming1118@gmail.com", "yongming1024");
                //gmail 专有配置 开始
                SmtpMail.Port = 587;
                SmtpMail.EnableSsl = true;
                //gmail 专有配置 结束
                SmtpMail.Send(mailObj);
            }
            catch (Exception ex)
            {
            }

        }

        private List<Product> listProduct;
        private int ilistProduct = 0;
        private List<catalogProductReturnEntity> listRtnProduct = new List<catalogProductReturnEntity>();
        private int ilistRtnProduct = 0;
        private void GetNextProduct(out string strPic, out string strUrl)
        {
            if (listProduct == null)
                listProduct = ProductsDb.DbMysql.GetAllProducts();
            while (ilistProduct < listProduct.Count() - 1)
            {
                var product = listProduct[ilistProduct];
                if (product.EbaoInventory > 0 && product.Status[0] == 49)
                {
                    if (
                        ProductImageApi.IsURLFileExists(
                            @"http://s526cb205e97ef.img.gostorego.com/809E82/cdn/media/s5/26/cb/20/5e/97/ef/catalog/product/cache/1/small_image/76x76/9df78eab33525d08d6e5fb8d27136e95/S/S/" +
                            product.SKU + "0.jpg"))
                    {
                        var catalogProductReturnEntity = StoreApi.Api.GetProductInfo(product.SKU,
                                                                                     new string[2] {"sku", "url_path"});
                        listRtnProduct.Add(catalogProductReturnEntity);
                        ilistProduct++;
                        break;
                    }
                }
                ilistProduct++;
            }
            if (ilistRtnProduct >=  listRtnProduct.Count())
            {
                ilistRtnProduct = 0;
            }
            strPic = @"http://s526cb205e97ef.img.gostorego.com/809E82/cdn/media/s5/26/cb/20/5e/97/ef/catalog/product/cache/1/small_image/76x76/9df78eab33525d08d6e5fb8d27136e95/S/S/" + listRtnProduct[ilistRtnProduct].sku + "0.jpg";
            strUrl = @"http://www.maibey.com/" + listRtnProduct[ilistRtnProduct].url_key + ".html";
            ilistRtnProduct++;
        }

        private void SentMaibeyEmail(EmailInfo email)
        {

            try
            {
                string title;
                string content;
                MailAddress sendor;
                GetEmailInfo(email, out title, out content, out sendor);

                System.Net.Mail.MailMessage mailObj = new System.Net.Mail.MailMessage();
                mailObj.IsBodyHtml = true;
                mailObj.Subject = title;
                mailObj.Body = content;
                mailObj.To.Add(new MailAddress(email.Email, email.Name));
                System.Net.Mail.SmtpClient SmtpMail = new SmtpClient("mail.maibey.com");
                mailObj.From = sendor;
                SmtpMail.Credentials = new System.Net.NetworkCredential(sendor.Address, "1234567");
                //gmail 专有配置 开始
                //gmail 专有配置 结束
                SmtpMail.Send(mailObj);
            }
            catch (Exception ex)
            {
            }
        }

        private string GetEmailTableName()
        {
            return this.textBoxEmailTableName.Text;
        }
        Timer timer = new Timer();
        private int indexEmail = 0;
        private List<EmailInfo> listEmail;
        private List<EmailInfo> ReListByDomain(List<EmailInfo> list)
        {
            var diclistEmail = new Dictionary<string, List<EmailInfo>>();
            var dicIndex = new Dictionary<string, int>();
            var listDomain = new List<string>();
            foreach (EmailInfo emailInfo in listEmail)
            {
                if (emailInfo.Domain.ToLower().EndsWith("rr.com")) emailInfo.Domain = "rr.com";
                if (!diclistEmail.ContainsKey(emailInfo.Domain))
                {
                    diclistEmail.Add(emailInfo.Domain, new List<EmailInfo>());
                    dicIndex.Add(emailInfo.Domain, 0);
                    listDomain.Add(emailInfo.Domain);
                }
                diclistEmail[emailInfo.Domain].Add(emailInfo);
            }
            int i = 0;
            var listRtn = new List<EmailInfo>();
            while (listDomain.Count > 0)
            {

                int iListDomain = 0;
                while (iListDomain < listDomain.Count)
                {
                    if (i >= diclistEmail[listDomain[iListDomain]].Count)
                    {
                        listDomain.Remove(listDomain[iListDomain]);
                        continue;
                    }
                    listRtn.Add(diclistEmail[listDomain[iListDomain]][i]);
                    iListDomain++;
                }
                i++;
            }


            return listRtn;

        }
        private void buttonSent_Click(object sender, EventArgs e)
        {
            listEmail = EmailsDb.DbMysql.GetEmailsList(GetEmailTableName());
            listEmail = ReListByDomain(listEmail);
            for (int i = 0; i < listEmail.Count -1; i++)
            {
                var emailInfo = listEmail[i];
                if (emailInfo.Email.ToLower().EndsWith("@qq.com")) continue;
                if (emailInfo.Email.ToLower().EndsWith("@comcast.net")) continue;
                if (emailInfo.Email.ToLower().EndsWith("@verizon.net")) continue;
                //if (emailInfo.Email.ToLower().EndsWith("@aol.com")) continue;
                //if (emailInfo.Email.ToLower().EndsWith("@cox.net")) continue;
                //if (emailInfo.Email.ToLower().EndsWith("@sfmail.net")) continue;
                //if (emailInfo.Email.ToLower().EndsWith("rr.com")) continue;
                //if (emailInfo.Email.ToLower().EndsWith("@charter.net")) continue;
                //if (emailInfo.Email.ToLower().EndsWith(".fsnet.co.uk")) continue;
                //if (emailInfo.Email.ToLower().EndsWith("@zoominternet.net")) continue;
                System.Threading.Thread.Sleep(3000);
                SentMaibeyEmail(emailInfo);
                EmailsDb.DbMysql.UpdateEmailDeliveryStatus(emailInfo.Email, GetEmailTableName());
            }
            listEmail = EmailsDb.DbMysql.GetEmailsList(GetEmailTableName());
            timer.Stop();
            timer.Interval = 3000;
            timer.Tick -= timer_Tick;
            timer.Tick += timer_Tick;
            indexEmail = 0;
            timer.Start();

        }

        private string GetProductLinkHtml(string strPic, string strUrl)
        {
            return "<td><a href=\"" + strUrl + "\"><img src=\"" + strPic  + "\"/></a></td>";
        }
        List<MailAddress> listAddress ;
        private int ilistAddress = 0;
        List<string> listEmailTitle;
        private int ilistEmailTitle = 0;
        private void GetEmailInfo(EmailInfo emailInfo, out string strTitle, out string strContent, out MailAddress sendor)
        {
            if (listEmailTitle == null)
            {
                listEmailTitle = new List<string>();
                listEmailTitle.Add("Mai Bey The 925 Sterling Silver Jewelry!");
                listEmailTitle.Add("Don't Miss Out Our Biggest Deals!");
                listEmailTitle.Add("This just for You!");
                listEmailTitle.Add("925 Sterling Silver Jewelry just for You!");
                listEmailTitle.Add("Time To Discover Gifts！");
                listEmailTitle.Add("Only for Our VIP Members！");
                listEmailTitle.Add("New Pandora Style Valentine Beads Are Here！");
                listEmailTitle.Add("Shop Our Adorable New Spring Jewelry！");
                listEmailTitle.Add("Shop Best Prices Now!");
                listEmailTitle.Add("Check out Now!");
                listEmailTitle.Add("Make Your Move!");
                listEmailTitle.Add("Shop Best Prices Now The 925 Sterling Silver Jewelry!");
                listEmailTitle.Add("Check out Now The 925 Sterling Silver Jewelry!");
                listEmailTitle.Add("Make Your Move The 925 Sterling Silver Jewelry!");
                listEmailTitle.Add("The 925 Sterling Silver Jewelry Shop Best Prices Now!");
                listEmailTitle.Add("The 925 Sterling Silver Jewelry Check out Now!");
                listEmailTitle.Add("The 925 Sterling Silver Jewelry Make Your Move!");
                listEmailTitle.Add("Shop Our Adorable New Spring 925 Sterling Silver Jewelry！");
            } 
            if(ilistEmailTitle >= listEmailTitle.Count) ilistEmailTitle = 0;
            strTitle = emailInfo.Name + "," + listEmailTitle[ilistEmailTitle++];
            string strPic;
            string strUrl;
            GetNextProduct(out strPic, out strUrl);
            var subhtml = GetProductLinkHtml(strPic, strUrl);
            GetNextProduct(out strPic, out strUrl);
            subhtml += GetProductLinkHtml(strPic, strUrl);
            GetNextProduct(out strPic, out strUrl);
            subhtml += GetProductLinkHtml(strPic, strUrl);
            GetNextProduct(out strPic, out strUrl);
            subhtml += GetProductLinkHtml(strPic, strUrl);
            GetNextProduct(out strPic, out strUrl);
            subhtml += GetProductLinkHtml(strPic, strUrl);
            GetNextProduct(out strPic, out strUrl);
            subhtml += GetProductLinkHtml(strPic, strUrl);
            GetNextProduct(out strPic, out strUrl);
            subhtml += GetProductLinkHtml(strPic, strUrl);
            GetNextProduct(out strPic, out strUrl);
            subhtml += GetProductLinkHtml(strPic, strUrl);
            strContent = this.textBoxEmailContent.Text.Replace("%%Title%%", strTitle);
            strContent = strContent.Replace("%%ProductLinkHtml%%", subhtml);
            if (listAddress == null)
            {
                listAddress = new List<MailAddress>();
                listAddress.Add(new MailAddress("sales@maibey.com", "Mai Bey", System.Text.Encoding.UTF8));
                listAddress.Add(new MailAddress("hillson@maibey.com", "Mai Bey", System.Text.Encoding.UTF8));
                listAddress.Add(new MailAddress("sales1@maibey.com", "Mai Bey", System.Text.Encoding.UTF8));
                listAddress.Add(new MailAddress("sakura@maibey.com", "Mai Bey", System.Text.Encoding.UTF8));
                listAddress.Add(new MailAddress("sales2@maibey.com", "Mai Bey", System.Text.Encoding.UTF8));
                listAddress.Add(new MailAddress("sales3@maibey.com", "Mai Bey", System.Text.Encoding.UTF8));
                listAddress.Add(new MailAddress("lip870709@maibey.com", "Mai Bey", System.Text.Encoding.UTF8));
                listAddress.Add(new MailAddress("rainday@maibey.com", "Mai Bey", System.Text.Encoding.UTF8));
                listAddress.Add(new MailAddress("sales4@maibey.com", "Mai Bey", System.Text.Encoding.UTF8));
                listAddress.Add(new MailAddress("eva@maibey.com", "Mai Bey", System.Text.Encoding.UTF8));
                listAddress.Add(new MailAddress("sales5@maibey.com", "Mai Bey", System.Text.Encoding.UTF8));
                listAddress.Add(new MailAddress("minkey@maibey.com", "Mai Bey", System.Text.Encoding.UTF8));
                listAddress.Add(new MailAddress("sales6@maibey.com", "Mai Bey", System.Text.Encoding.UTF8));
                listAddress.Add(new MailAddress("alagong@maibey.com", "Mai Bey", System.Text.Encoding.UTF8));
                listAddress.Add(new MailAddress("sales7@maibey.com", "Mai Bey", System.Text.Encoding.UTF8));
                listAddress.Add(new MailAddress("benjam@maibey.com", "Mai Bey", System.Text.Encoding.UTF8));
                listAddress.Add(new MailAddress("sales8@maibey.com", "Mai Bey", System.Text.Encoding.UTF8));
                listAddress.Add(new MailAddress("alex@maibey.com", "Mai Bey", System.Text.Encoding.UTF8));
                listAddress.Add(new MailAddress("alan.hu@maibey.com", "Mai Bey", System.Text.Encoding.UTF8));
                listAddress.Add(new MailAddress("jason.song@maibey.com", "Mai Bey", System.Text.Encoding.UTF8));
            }
            if (ilistAddress >= listAddress.Count) ilistAddress = 0;
            sendor = listAddress[ilistAddress++];
        }
        void timer_Tick(object sender, EventArgs e)
        {
            timer.Stop();
            var emailInfo = listEmail[indexEmail];
            indexEmail++;
            SentMaibeyEmail(emailInfo);
            EmailsDb.DbMysql.UpdateEmailDeliveryStatus(emailInfo.Email, GetEmailTableName());
            timer.Interval = 300; 
            timer.Start();
        }
        #endregion 


    }
}
